package com.huayu.io.aio;


import com.sun.scenario.effect.impl.sw.sse.SSEBlend_SRC_OUTPeer;

import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;
import java.util.concurrent.ExecutionException;

public class ServerCompletionHandler implements CompletionHandler<AsynchronousSocketChannel,Server> {


    @Override
    public void completed(AsynchronousSocketChannel result, Server attachment) {
        attachment.assc.accept(attachment,this);
        read(result);
    }

    @Override
    public void failed(Throwable exc, Server attachment) {
        exc.printStackTrace();
    }

    private void read(AsynchronousSocketChannel channel){
        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
        channel.read(byteBuffer, byteBuffer, new CompletionHandler<Integer, ByteBuffer>() {
            @Override
            public void completed(Integer result, ByteBuffer attachment) {
               attachment.flip();
               System.out.printf("服务端接收到：%s",new String(attachment.array()));
               write(channel,"接收到消息了");


            }

            @Override
            public void failed(Throwable exc, ByteBuffer attachment) {

            }
        });



    }

    private void write(AsynchronousSocketChannel channel,String data){
        try {
            ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
            byteBuffer.put(data.getBytes());
            byteBuffer.flip();
            Integer integer = channel.write(byteBuffer).get();
            System.out.println(integer+"================");
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }

    }
}
